package com.kude.manager.support;

import com.kude.manager.ConditionException;



public class QuerySupport implements IQuerySupport{
	
	private String whereSql="";
	private String groupBySql="";
	private String orderBySql="";
	
	public String encode() {
		String condition = "";
		if(!whereSql.equals("")) {
			condition += " where "+whereSql; 
		}
		if(!groupBySql.equals("")) {
			condition += " group by "+groupBySql;
		}
		if(!orderBySql.equals("")) {
			condition += " order by "+orderBySql;
		}
		return condition;
	}
	
	public IQuerySupport and(AbstractCondition condition) throws ConditionException{
		if(condition == null) {
			throw new ConditionException("条件参数不能为空");
		}
		if((whereSql).equals("")) {
			this.whereSql = condition.toSql();
		}else {
			this.whereSql += " and "+condition.toSql();
		}
		return this;
	}
	
	public IQuerySupport or(AbstractCondition condition) throws ConditionException{
		if(condition == null) {
			throw new ConditionException("条件参数不能为空");
		}
		if((whereSql).equals("")) {
			this.whereSql = condition.toSql();
		}else {
			this.whereSql += " or "+condition.toSql();
		}
		return this;
	}


	public IQuerySupport groupBy(AbstractCondition condition) throws ConditionException{
		if(condition == null) {
			throw new ConditionException("条件参数不能为空");
		}
		if(!(condition instanceof GroupByCondition)) {
			throw new ConditionException("参数不是GroupCondition类型");
		}
		this.groupBySql += condition.toSql();
		return this;
	}

	public IQuerySupport orderBy(AbstractCondition condition) throws ConditionException{
		if(condition == null) {
			throw new ConditionException("条件参数不能为空");
		}
		if(!(condition instanceof OrderByCondition)) {
			throw new ConditionException("条件参数不是OrderByCondition类型");
		}
		this.orderBySql += condition.toSql();
		return this;
	}

	public IQuerySupport Wrap() {
		this.whereSql=new StringBuilder().append("( ").append(this.whereSql).append(" )").toString();
		return this;
	}
	
}
